/*
 * File Name：SerializeUtil.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： SerializeUtil.java
 * Modify By：pla-gysu
 * Modify Date：2015年6月26日
 * Modify Type：Add
 */
package com.ciwong.epaper.util;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.ciwong.libs.utils.CWSys;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.ThreadTask;

import java.io.IOException;
import java.io.Serializable;

/**
 * 序列化Dao
 *
 * @author pla-gysu
 */
public class SerializableManager {
    //    private static final String TAG = SerializableManager.class.getSimpleName();
    private static final String TAG = "retryscore2";

    private static SerializableManager instance;

    private Handler mHandler = new Handler(Looper.getMainLooper());

    private SerializableManager() {

    }

    /**
     * 获取唯一实例
     *
     * @return 唯一实例
     */
    public static SerializableManager getInstance() {
        if (instance == null) {
            syncInit();
        }
        return instance;
    }

    /**
     * 实例化对象
     */
    private static synchronized void syncInit() {
        if (instance == null) {
            instance = new SerializableManager();
        }
    }

    /**
     * 序列化(区分用户)
     *
     * @param key          {@link SerializeKey} 序列化key
     * @param serializable 要序列化的list
     */
    public void serialize(String key, Serializable serializable) {
        serialize(key, serializable, true);
    }

    /**
     * 序列化
     *
     * @param key          {@link SerializeKey} 序列化key
     * @param serializable 要序列化的数据
     * @param isDiffUser   是否区分用户
     */
    public void serialize(final String key, final Serializable serializable,
                          final boolean isDiffUser) {
        if (!TextUtils.isEmpty(key)) {
//            Log.d(TAG, "前面序列化：" + getUserId(isDiffUser));
            ThreadTask.getInstance().executorDBThread(new Runnable() {

                @Override
                public void run() {
                    try {
                        synchronized (SerializableManager.this) {
                            CWSys.setSharedSerializable(key + getUserId(isDiffUser), serializable);
//                            Log.d(TAG, "序列化：" + key);
                        }
                    } catch (Exception e) {
                        Log.d(TAG, "########序列化异常##########" + e.getMessage());
                        e.printStackTrace();
                    }
                }
            }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
        }
    }

    /**
     * 获取用户id
     *
     * @param isDiffUser 是否区分用户
     * @return
     */
    public String getUserId(boolean isDiffUser) {
        if (isDiffUser) {
            long userId = CWSys.getSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0);
            return "," + userId;
        }
        return "";
    }


    public String getUserPhone(boolean isDiffUser) {
        if (isDiffUser) {
            String userPhone = CWSys.getSharedString(BaseConstants.SHARE_PRE_CURR_LOGIN_USER_PHONE + getUserId(true), null);
            return userPhone;
        }
        return null;
    }

    /**
     * 获取是否首次登录
     *
     * @param isDiffUser
     * @return
     */
    public boolean getIsFirstLogin(boolean isDiffUser) {
        if (isDiffUser) {
            boolean isFirst = CWSys.getSharedBoolean(BaseConstants.SHARE_KEY_IS_FIRST_LOGIN + getUserId(true), true);
            return isFirst;
        }
        return true;

    }

    /**
     * ShowTip相关
     * 默认为false
     *
     * @param isDiffUser
     * @return
     */
    public boolean getIsShowTip(boolean isDiffUser) {
        if (isDiffUser) {
            boolean isFirst = CWSys.getSharedBoolean(BaseConstants.SHARE_KEY_IS_FIRST_SHOW_TIP + getUserId(true), false);
            return isFirst;
        }
        return false;

    }

    /**
     * ShowTip，书柜页面相关
     * 默认为false
     *
     * @param isDiffUser
     * @return
     */
    public boolean getIsFirstShowAddTip(boolean isDiffUser) {
        if (isDiffUser) {
            boolean isFirst = CWSys.getSharedBoolean(BaseConstants.SHARE_KEY_IS_FIRST_SHOW_ADD_TIP + getUserId(true), false);
            return isFirst;
        }
        return false;

    }


    /**
     * 反序列化(区分用户)
     *
     * @param key      {@link SerializeKey} 序列化key
     * @param callBack
     */
    public void deSerialize(final String key, final BaseCallBack callBack) {
        deSerialize(key, callBack, true);
    }

    /**
     * 反序列化
     *
     * @param key        {@link SerializeKey} 序列化key
     * @param callBack   回调
     * @param isDiffUser 是否区分用户
     */
    public void deSerialize(final String key, final BaseCallBack callBack,
                            final boolean isDiffUser) {
        if (!TextUtils.isEmpty(key)) {
            ThreadTask.getInstance().executorDBThread(new Runnable() {

                @Override
                public void run() {
                    try {
                        final Object object;
                        synchronized (SerializableManager.this) {
                            object = CWSys.getSharedSerializable(
                                    key + getUserId(isDiffUser));
                        }
                        if (callBack != null) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    callBack.success(object);
                                }
                            });
                        }
                    } catch (final IOException e) {
                        e.printStackTrace();
                        if (callBack != null) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    callBack.failed(-6, e.getMessage());
                                }
                            });
                        }
                    } catch (final Exception e) {
                        e.printStackTrace();
                        if (callBack != null) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    callBack.failed(-5, e.getMessage());
                                }
                            });
                        }
                    }
                }
            }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
        } else {
            if (callBack != null) {
                callBack.failed(-7, "Key is null！");
            }
        }
    }


    /**
     * 序列化Key
     */
    public class SerializeKey {
        /**
         * 已登录用户集合
         */
        public static final String SHARE_KEY_LOGIN_ACCOUNT_LIST = "SHARE_KEY_LOGIN_ACCOUNT_LIST";

        /**
         * 最新的用户登录集合
         * 为了解决账号记不住的问题,统一采取新的存取方式
         */
        public static final String SHARE_KEY_USER_ACCOUNT_LIST = "SHARE_KEY_USER_ACCOUNT_LIST";
        /**
         * 当前登陆用户服务信息详情列表
         */
        public static final String SHARE_KEY_SERVICE_DETAIL_LIST = "SHARE_KEY_SERVICE_DETAIL_LIST";

        /**
         * 当前登陆用户服务信息详情列表
         */
        public static final String SHARE_KEY_SERVICE_DETAIL_EXIST_LIST = "SHARE_KEY_SERVICE_DETAIL_EXIST_LIST";

        /**
         * 当前登陆用户服务信息详情
         */
        public static final String SHARE_KEY_SERVICE_DETAIL = "SHARE_KEY_SERVICE_DETAIL";

        /**
         * 电子报服务信息列表
         */
        public static final String SHARE_KEY_SERVICE_LIST = "SHARE_KEY_SERVICE_LIST";

        /**
         * 电子报服务信息
         */
        public static final String SHARE_KEY_SERVICE = "SHARE_KEY_SERVICE";

        /**
         * 当前登陆用户全部学校详情
         */
        public static final String SHARE_KEY_ALL_SCHOOL = "SHARE_KEY_ALL_SCHOOL";

        /**
         * 当前登陆用户默认学校详情
         */
        public static final String SHARE_KEY_CHOOSE_SCHOOL = "SHARE_KEY_CHOOSE_SCHOOL";


        /**
         * 当前登陆用户背景图片
         */
        public static final String SHARE_KEY_USER_BG = "SHARE_KEY_USER_BG";

        /**
         * 电子报书籍列表信息
         */
        public static final String SHARE_KEY_NEWSPAPER_LIST = "SHARE_KEY_NEWSPAPER_LIST";

        /**
         * 最近学习的电子报
         */
        public static final String SHARE_KEY_LATER_NEWSPAPER = "SHARE_KEY_LATER_NEWSPAPER";

        /**
         * 不同模块作业提交情况统计
         */
        public static final String SHARE_KEY_MODULE_SUBMIT_STATISTICS = "SHARE_KEY_MODULE_SUBMIT_STATISTICS";

        /**
         * 作业通知列表
         */
        public static final String SHARE_KEY_NOTIFICATION_LIST = "SHARE_KEY_NOTIFICATION_LIST";

        /**
         * 打卡作业通知列表
         */
        public static final String SHARE_KEY_USERDKWORK_LIST = "SHARE_KEY_USERDKWORK_LIST";

        /**
         * 作业通知列表  已经完成的作业
         */
        public static final String SHARE_KEY_HAS_DONE_NOTIFICATION_LIST = "SHARE_KEY_HAS_DONE_NOTIFICATION_LIST";

        /**
         * 作业错题列表
         */
        public static final String SHARE_KEY_NOTIFICATION_ERROR_LIST = "SHARE_KEY_NOTIFICATION_ERROR_LIST";

        /**
         * 更早作业
         */
        public static final String SHARE_KEY_EARLIER_NOTIFICATION_LIST = "SHARE_KEY_EARLIER_NOTIFICATION_LIST";

        /**
         * 自主学习
         */
        public static final String SHARE_KEY_AUTONOMIC_STUDY_LIST = "SHARE_KEY_AUTONOMIC_STUDY_LIST";

        /**
         * 新书桌首页
         */
        public static final String SHARE_KEY_BOOK_DESK_HOME_PAGE = "SHARE_KEY_BOOK_DESK_HOME_PAGE";
        /**
         * 新书桌首页目录
         */
        public static final String SHARE_KEY_BOOK_DESK_CATALOGUE = "SHARE_KEY_BOOK_DESK_CATALOGUE";


        /**
         * 班级列表
         */
        public static final String SHARE_KEY_CLASS_LIST = "SHARE_KEY_CLASS_LIST";

        /**
         * 默认班级
         */
        public static final String SHARE_KEY_CLASS_DEFAULT = "SHARE_KEY_CLASS_DEFAULT";

        /**
         * 服务售价列表
         */
        public static final String SHARE_KEY_SERVICE_PRICE_LIST = "SHARE_KEY_SERVICE_PRICE_LIST";

        /**
         * 做作业记录
         */
        public static final String SHARE_KEY_DO_WORK_RECORD = "SHARE_KEY_DO_WORK_RECORD";


        public static final String SHARE_KEY_ONLINE_ANSWER_RECORD = "SHARE_KEY_ONLINE_ANSWER_RECORD";

        public static final String SHARE_KEY_ONLINE_ANSWER_COMMIT_RECORD = "SHARE_KEY_ONLINE_ANSWER_COMMIT_RECORD";

        /**
         * 答案记录
         */
        public static final String SHARE_KEY_ANSWER_RECORD = "SHARE_KEY_ANSWER_RECORD";
        /**
         * 新听说模考用户答案及音频上传状态列表记录
         */
        public static final String NEW_LISTENSPEAK_ANSWER_RECORD = "NEW_LISTENSPEAK_ANSWER_RECORD";
        /**
         * 做作业UUID
         */
        public static final String SHARE_KEY_UUID_RECORD = "SHARE_KEY_DO_WORK_UUID";
        /**
         * 做作业开始时间
         */
        public static final String SHARE_KEY_START_DATE = "SHARE_KEY_START_DATE";

        /**
         * 做作业开始时间是否上报
         */
        public static final String SHARE_KEY_START_DATE_IS_UPLOAD = "SHARE_KEY_START_DATE_IS_UPLOAD";
        /**
         * 背单词复习单词索引
         */
        public static final String CURRENT_REVIEW_INDEX = "CURRENT_REVIEW_INDEX";
        /**
         * 背单词
         */
        public static final String CURRENR_NEW_INDEX = "CURRENR_NEW_INDEX";

        /**
         * 背单词新学单词 复习记录
         */
        public static final String CURRENR_NEW_REVIEW_TODAY = "CURRENR_NEW_REVIEW_TODAY";

        /**
         * 背单词复习新学单词 已经完成的索引
         */
        public static final String COMPETE_WORD_INDEX = "COMPETE_WORD_INDEX";
        //需新学单词
        public static final String NEW_WORDS_TO_STUDY = "NEW_WORDS_TO_STUDY";
        //需复习单词个数
        public static final String REVIEW_WORDS_TO_REVIEW = "REVIEW_WORDS_TO_REVIEW";
        //学习模式
        public static final String STUDY_TYPE = "STUDY_TYPE";


        /**
         * 背单词新学单词 已经完成的索引
         */
        public static final String TODAY_NEW_WORD_INDEX = "TODAY_NEW_WORD_INDEX";
        /**
         * 当前计划个数
         */
        public static final String CURRENT_WORD_PLAN_COUNT = "CURRENT_WORD_PLAN_COUNT";
        /**
         * 今天是否已经完成过单词计划
         */
        public static final String TODAY_HAS_COMPLETE_PALAN = "TODAY_HAS_COMPLETE_PALAN";
        /**
         * 背单词当前学习计划中的bookId
         */
        public static final String CURRENT_PLAIN_BOOK_ID = "CURRENT_PLAIN_BOOK_ID";
        /**
         * 当前计划完成时间
         */
        public static final String WORD_COMPLETE_TIME = "WORD_COMPLETE_TIME";


        /**
         * 做作业UUID
         */
        public static final String SHARE_KEY_UUID_RECORD_WORD = "SHARE_KEY_UUID_RECORD_WORD";


        /**
         * 做作业UUID
         */
        public static final String SHARE_KEY_UUID_DUBBING = "SHARE_KEY_UUID_DUBBING";

        /**
         * 做作业UUID
         */
        public static final String SUBMIT_STATE = "SUBMIT_STATE";

        /**
         * 句子跟读记录(用于显示已跟读过的UI)
         */
        public static final String SHARE_KEY_SENTENCE_RECORD = "SHARE_KEY_SENTENCE_RECORD";

        /**
         * 听说模考保存当前大题题号
         */
        public static final String SHARE_KEY_QUESTION_NO = "SHARE_KEY_QUESTION_NO";

        /**
         * 听说模考保存当前小题题号
         */
        public static final String SHARE_KEY_SMALL_QUESTION_NO = "SHARE_KEY_SMALL_QUESTION_NO";

        /**
         * 听说模考保存当前题目总下标
         */
        public static final String SHARE_KEY_TOTAL_NO = "SHARE_KEY_TOTAL_NO";

        /**
         * 听说模考保存当前状态
         */
        public static final String SHARE_KEY_STATUS_NO = "SHARE_KEY_STATUS_NO";

        /**
         * 听说模考是否到过重做页面
         */
        public static final String SHARE_KEY_BEEN_TO_REDO_PAGE = "SHARE_KEY_BEEN_TO_REDO_PAGE";

        /**
         * 听说模考是否到过结果页面
         */
        public static final String SHARE_KEY_BEEN_TO_RESULT_PAGE = "SHARE_KEY_BEEN_TO_RESULT_PAGE";

        /**
         * 听说模考是否需要重新开始答题
         */
        public static final String SHARE_KEY_IS_RESTART = "SHARE_KEY_IS_RESTART";

        /**
         * 题目总数目
         */
        public static final String SHARE_KEY_QUESTION_COUNT = "SHARE_KEY_QUESTION_COUNT";

        /**
         * 听说模考是否做记录
         */
        public static final String SHARE_KEY_IS_DO_RECORD = "SHARE_KEY_IS_DO_RECORD";

        /**
         * 做作业用时（秒）
         */
        public static final String SHARE_KEY_DO_WORK_TIME = "SHARE_KEY_TIME";


        /**
         * 做作业开始时间（秒）
         */
        public static final String SHARE_KEY_DO_WORK_START_TIME = "SHARE_KEY_START_TIME";

        /**
         * 系统时间
         */
        public static final String SHARE_KET_WORK_NOW_DATA = "SHARE_KET_WORK_NOW_DATA";


        /**
         * 开头作文评测临时类
         */
        public static final String SHARE_KEY_TEMP_LS = "SHARE_KEY_TEMP_LS";

        /**
         * 书柜首页选中的书籍ID
         */
        public static final String SHARE_KEY_BOOK_ID = "SHARE_KEY_BOOK_ID";

        /**
         * 是否需要自动跳转到服务商城页面
         */
        public static final String SHARE_KEY_BOOKCASE_AUTO_SERVICE_SHOP = "SHARE_KEY_BOOKCASE_AUTO_SERVICE_SHOP";

        /**
         * 是否是首次显示书柜帮助信息
         */
        public static final String SHARE_KEY_BOOKCASE_HELP_TIP = "SHARE_KEY_BOOKCASE_HELP_TIP";

        /**
         * 是否匹配过年级
         */
        public static final String SHARE_KEY_IS_MATCH_GRADE = "SHARE_KEY_IS_MATCH_GRADE";

        /**
         * 听说模考批改答案
         */
        public static final String SHARE_KEY_LISTEN_SPEAK_WORK_CORRECT_ANSWER = "SHARE_KEY_LISTEN_SPEAK_WORK_CORRECT_ANSWER";
        /**
         * 未读消息数量
         */
        public static final String SHARE_KEY_NO_READ_MSG_COUNT_NEW = "SHARE_KEY_NO_READ_MSG_COUNT_NEW";
        /**
         * 本地消息列表
         */
        public static final String SHARE_KEY_MSG_LIST_NEW = "SHARE_KEY_MSG_LIST_NEW";

        public static final String SHARE_KEY_MSG_POSTBEAN = "SHARE_KEY_MSG_POSTBEAN";
        /**
         * 本地消息列表(根据发送者ID)
         */
        public static final String SHARE_KEY_MSG_LIST_SENDERID = "SHARE_KEY_MSG_LIST_SENDERID";
        /**
         * 作业详情
         */
        public static final String SHARE_KEY_MSG_WORK_DETAIL = "SHARE_KEY_MSG_WORK_DETAIL";
        /**
         * 书籍层级目录
         */
        public static final String SHARE_KEY_BOOK_CATALOGUE = "SHARE_KEY_BOOK_CATALOGUE";

        /**
         * 书籍层级目录
         */
        public static final String SHARE_KEY_BOOK_CHAPTER = "SHARE_KEY_BOOK_CHAPTER";

        /**
         * 书籍层级目录
         */
        public static final String SHARE_KEY_BOOK_SECTION_CHAPTER = "SHARE_KEY_BOOK_SECTION_CHAPTER";


        /**
         * 书籍层级目录
         */
        public static final String SHARE_KEY_BOOK_KAOSHI = "SHARE_KEY_BOOK_KAOSHI";

        /**
         * 根据服务ID获取的书籍列表
         */
        public static final String SHARE_KEY_BOOK_SERVICEID = "SHARE_KEY_BOOK_SERVICEID";
        /**
         * 书桌目录
         */
        public static final String SHARE_KEY_BOOKCASE = "SHARE_KEY_BOOKCASE";
        /**
         * 广告信息
         */
        public static final String SHARE_KEY_ADVERST = "SHARE_KEY_ADVERST";

        /**
         * 评分失败记录
         */
        public static final String SHARE_KEY_FAIL_ENGINE_EVALUATE = "SHARE_KEY_FAIL_ENGINE_EVALUATE";

        /**
         * 失败评分或者提交的答案的id
         */
        public static final String SHARE_KEY_FAIL_ANSWER_ID = "SHARE_KEY_FAIL_ANSWER_ID";

        /**
         * 作答音频的上传状态
         */
        public static final String SHARE_KEY_RECORD_FILE_UPLOAD_STATE = "SHARE_KEY_RECORD_FILE_UPLOAD_STATE";


        public static final String LOGIN_ERROR_TAG = "USER_ERROR_LOG";

        /**
         * 句子跟读状态
         */
        public static final String SHARE_KEY_SENTENCE_STATE = "SHARE_KEY_SENTENCE_STATE";


        /**
         * zip 包更新信息列表
         */
        public static final String SHARE_KEY_ZIP_PACKAGE_LIST_INFO = "SHARE_KEY_ZIP_PACKAGE_LIST_INFO";

        /**
         * 当前登陆用户年级信息
         */
        public static final String SHARE_KEY_GRADE_ID = "SHARE_KEY_GRADE_ID";


        /**
         * 当前书城首页数据
         */
        public static final String SHARE_KEY_BOOKSTORE_LIST = "SHARE_KEY_BOOKSTORE_LIST";


        //选中词汇页展示的数据
        public static final String SHARE_KEY_SELECT_JIAOCAI_VERSIONS = "SHARE_KEY_SELECT_JIAOCAI_VERSIONS";
        public static final String SHARE_KEY_PLAN_AND_WORD_LIST = "SHARE_KEY_PLAN_AND_WORD_LIST";


    }
}
